<html>
  <head>
    <title>DeviceMotion test</title>
    <script type="text/javascript">
      const expectedInterval = Math.floor(1000 / 60);
      const kRadiansToDegrees = 180 / Math.PI;
      let eventTimeoutId; // To be set in start().

      function checkMotionEvent(event) {
        return event.acceleration.x == 1 &&
               event.acceleration.y == 2 &&
               event.acceleration.z == 3 &&
               event.accelerationIncludingGravity.x == 4 &&
               event.accelerationIncludingGravity.y == 5 &&
               event.accelerationIncludingGravity.z == 6 &&
               event.rotationRate.alpha == 7 * kRadiansToDegrees &&
               event.rotationRate.beta == 8 * kRadiansToDegrees &&
               event.rotationRate.gamma == 9 * kRadiansToDegrees &&
               event.interval == expectedInterval;
      }

      function onMotion(event) {
        if (checkMotionEvent(event)) {
          window.removeEventListener('devicemotion', onMotion);
          window.clearTimeout(eventTimeoutId);
          pass();
        } else {
          fail();
        }
      }

      function pass() {
        document.getElementById('status').innerHTML = 'PASS';
        document.location = '#pass';
      }

      function fail() {
        document.location = '#fail';
      }

      function failOnTimeoutIfNeeded() {
        let params = new URLSearchParams(location.search);
        let timeout = Number(params.get("failure_timeout"));
        if (timeout > 0)
          eventTimeoutId = window.setTimeout(fail, timeout);
      }

      function start() {
        window.addEventListener('devicemotion', onMotion);
        failOnTimeoutIfNeeded();
      }
    </script>
  </head>
  <body onLoad="start()">
    <div id="status">FAIL</div>
  </body>
</html>
